/**
 * 
 */
package commons.base.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * 签名校验工具
 * @author yuan<cihang.yuan@happyelements.com>
 * @since 1.7
 */
public class SignUtil {

	/**
	 * 签名
	 * @param paramsMap
	 * @return
	 */
	public static String sign(Map<String, String> paramsMap, String appSecret){
		List<String> willHashKeys = new ArrayList<String>();
		 
		//获取要签名的key
		for(Object key: paramsMap.keySet()){
		    //注意排除 signature
		    if(! "signature".equals(key.toString())){
		        willHashKeys.add(key.toString());
		    }
		}
		
		//排序
		Collections.sort(willHashKeys);
		 
		String hashSource = "";
		 
		//拼装参数值
		for(String key: willHashKeys){
		    hashSource += paramsMap.get(key);
		}
		 
		//拼装密钥
		hashSource += appSecret;
		
		return DigestUtils.md5Hex(hashSource);
	}
	
	/**
	 * 校验签名
	 * @param request
	 * @param mySign
	 * @param appSecret
	 * @return
	 */
	public static boolean validSign(HttpServletRequest request, String appSecret){
		String otherSign = request.getParameter("signature");
		
		if(StringUtils.isBlank(otherSign)){
			return false;
		}
		
		String mySign = sign(allParams(request), appSecret);
		
		return mySign.equals(otherSign);
	}
	
	private static Map<String, String> allParams(HttpServletRequest request){
		Map<String, String> map = new HashMap<String, String>();
		
		for(String key: request.getParameterMap().keySet()){
			map.put(key, request.getParameter(key));
		}
		
		return map;
	}
}
